//
//  AppDelegate.swift
//  weibo
//
//  Created by sanya on 15/6/25.
//  Copyright © 2015年 sanya. All rights reserved.
//
import UIKit
import AFNetworking
// 全局变量记录用户信息
var sharedUserAccount =  UserAccount.loadAccount()
// 切换根控制器的通知
let SYSwitchRootVCNotification = "SYSwitchRootVCNotification"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        print(sharedUserAccount)
        // 设置网络
        setupNetwork()
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultController()
        // 设置外观
        setupAppearance()
        window?.makeKeyAndVisible()
        
        // 注册通知，监听控制器的跳转
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: SYSwitchRootVCNotification, object: nil)
        return true
    }
    // 控制器跳转
    func switchViewController(n:NSNotification){
        let isMainVc = n.object as! Bool
        window?.rootViewController = isMainVc ? MainViewController():WelcomeViewController()
    }
    // 默认服务器
    private func defaultController() -> UIViewController{
        // 判断是否登录
        if sharedUserAccount != nil {
            // 如果登录,检测新版本
            return isNewUpdate() ? NewFeatureViewController():WelcomeViewController()
        }
        
        return MainViewController()
    }
    // 检测更新
    private func isNewUpdate() -> Bool{
        // 1.从用户偏好中读取版本
        let versionKey = "versionKey"
        let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
//        print(sandBoxVersion)
        
        // 2.读取bundle中的版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)!
//        print(version)
        
        // 3.把当前版本写入到用户偏好中
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: versionKey)
        
        return version > sandBoxVersion
    
    }
    private func setupNetwork(){
        // 设置网络指示器
        
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        // 设置网络缓存
        let urlCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        
        NSURLCache.setSharedURLCache(urlCache)
    
    }
    // 设置外观
    private func setupAppearance(){
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
}

